package com.cos.hospital.ui.patient;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cos.hospital.R;
import com.cos.hospital.code.Code;
import com.cos.hospital.code.helper.MyOnFreshListener;
import com.cos.hospital.init.BaseActivity;
import com.cos.hospital.model.UHttp;
import com.cos.hospital.model.bean.ErrorBean;
import com.cos.hospital.model.bean.PatientListBean;
import com.cos.hospital.model.bean.ResultBean;
import com.cos.hospital.model.connector.HttpMsgListener;
import com.cos.hospital.tool.MyUtil;
import com.cos.hospital.tool.SPUtil;
import com.cos.hospital.tool.USnackbar;
import com.cos.hospital.tool.UTxt;
import com.cos.hospital.ui.main.QRCodeActivity;
import com.cos.hospital.ui.main.adapter.ReceptionAdapter;
import com.cos.hospital.ui.record.RecordEditActivity;
import com.cos.hospital.widget.MyDividerDecoration;
import com.cos.hospital.widget.ProgressDialog;
import com.google.gson.JsonObject;
import com.jude.utils.JUtils;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * 检索患者
 */
public class SearchAcitvity extends BaseActivity {
    @BindView(R.id.edt_search)
    EditText edt_search;
    @BindView(R.id.springView)
    SpringView springView;
    @BindView(R.id.rc)
    RecyclerView rc;
    private List<PatientListBean.ItemsBean> list;
    private BaseQuickAdapter adapter;
    private int pageIndex = 1;
    private TextView tv_create;
    private String content;

    @Override
    protected int layout() {
        return R.layout.activity_search;
    }

    @Override
    protected void init() {
        Intent intent = getIntent();
        content = intent.getStringExtra(Code.SP.CONTENT);
        boolean fromCure = intent.getBooleanExtra(Code.SP.FROMCURE, false);
        springView.setHeader(new DefaultHeader(this));
        list = new ArrayList<>();
        adapter = new ReceptionAdapter(list);
        adapter.openLoadAnimation();
        View inflate = View.inflate(this, R.layout.lay_empty_search, null);
        if (fromCure) {
            TextView tv = inflate.findViewById(R.id.tv);
            tv.setText("今天暂无治疗患者");
        }
        tv_create = inflate.findViewById(R.id.tv_create);
        adapter.setEmptyView(inflate);
        rc.setLayoutManager(new LinearLayoutManager(this));
        rc.addItemDecoration(new MyDividerDecoration(Color.TRANSPARENT, JUtils.dip2px(8)));
        rc.setAdapter(adapter);
        edt_search.setText(content);
    }

    @Override
    protected void logic() {
        springView.setListener(new MyOnFreshListener() {
            @Override
            public void onRefresh() {
                pageIndex = 1;
                getList();
            }
        });
        tv_create.setOnClickListener(view -> toCreatePatient());
        adapter.setOnItemClickListener((adapter, view, position) -> toPatientInfo(position));
        adapter.setOnItemChildClickListener((adapter, view, position) -> {
            switch (view.getId()) {
                case R.id.tv_write:
                    writeRecords(position);
                    break;
                case R.id.tv_send:
                    sendMessage(position);
                    break;
            }
        });
        adapter.setOnLoadMoreListener(() -> {
            pageIndex++;
            getList();
        }, rc);
        edt_search.setOnEditorActionListener((textView, actionId, keyEvent) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                content = textView.getText() + "";
                if (content.length() != 0) {
                    pageIndex = 1;
                    getList();
                } else {
                    USnackbar.showError(context, "请输入关键字");
                }
            }
            return false;
        });
        springView.callFreshDelay();
    }

    private void getList() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("keyword", content);
        jsonObject.addProperty("fldDoctorId", SPUtil.getUserId());
        jsonObject.addProperty("pageIndex", pageIndex);
        jsonObject.addProperty("pageSize", 10);
        UHttp.start(getServes().getPatientList(jsonObject), "患者搜索", new HttpMsgListener<ResultBean<PatientListBean>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                USnackbar.showWarning(context, describe);
            }

            @Override
            public void onFinish() {
                springView.onFinishFreshAndLoadDelay();
            }

            @Override
            public void onSuccess(ResultBean<PatientListBean> dto) {
                if (dto.isSuccess()) {
                    PatientListBean resultBean = dto.getResult();
                    if (resultBean != null) {
                        int pageIndex = resultBean.getPageIndex();
                        int pageSize = resultBean.getPageSize();
                        int recordCount = resultBean.getRecordCount();
                        if (pageIndex == 1) {
                            list.clear();
                            adapter.notifyDataSetChanged();
                        }
                        List<PatientListBean.ItemsBean> itemsBeanList = resultBean.getItems();
                        if (itemsBeanList != null && itemsBeanList.size() != 0) {
                            list.addAll(itemsBeanList);
                        }
                        int totalPageCount = MyUtil.getInstance().getTotalPageCount(pageSize, recordCount);
                        if (totalPageCount <= pageIndex) {
                            adapter.loadMoreEnd();
                        } else {
                            adapter.loadMoreComplete();
                        }
                    }
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    private void reception(int fldPatientId) {
        ProgressDialog.getInstance().startProgressDialog(context);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fldPatientId", fldPatientId);
        jsonObject.addProperty("fldDoctorId", SPUtil.getUserId());
        jsonObject.addProperty("fldEditId", SPUtil.getUserId());
        jsonObject.addProperty("fldMedicalFlag", 0);//初复诊标识 初诊 = 0,复诊 = 1
        UHttp.start(getServes().saveMedical(jsonObject), "病历保存(可同时签到接诊)", new HttpMsgListener<ResultBean<Integer>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                USnackbar.showWarning(context, describe);
            }

            @Override
            public void onFinish() {
                ProgressDialog.getInstance().stopProgressDialog();
            }

            @Override
            public void onSuccess(ResultBean<Integer> dto) {
                if (dto.isSuccess()) {
                    Intent intent = new Intent(context, RecordEditActivity.class);
                    intent.putExtra(Code.SP.ID, dto.getResult());
                    startActivity(intent);
                    sendBroadcast(new Intent(Code.Broadcast.CutoverToReception));
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    private void toCreatePatient() {
        startActivity(new Intent(this, PatientEditActivity.class));
    }

    private void toPatientInfo(int position) {
        PatientListBean.ItemsBean itemsBean = list.get(position);
        Intent intent = new Intent(context, PatientInfoActivity.class);
        int fldPatientId = itemsBean.getFldPatientId();
        intent.putExtra(Code.SP.FLDDOCTORID, itemsBean.getFldDoctorId());
        intent.putExtra(Code.SP.ID, fldPatientId);
        startActivity(intent);
    }

    private void writeRecords(int position) {
        PatientListBean.ItemsBean itemsBean = list.get(position);
        int fldState = itemsBean.getFldState();
        if (fldState != 2) {//患者签到状态，0：无状态，1：候诊中（患者签到），2：已接诊（患者已接诊）
            reception(itemsBean.getFldPatientId());
            return;
        }
        Intent intent = new Intent(context, RecordEditActivity.class);
        intent.putExtra(Code.SP.ID, itemsBean.getFldMedicalHistoryId());
        startActivity(intent);
    }

    private void sendMessage(int position) {
        PatientListBean.ItemsBean itemsBean = list.get(position);
        Intent intent = new Intent(context, SendMessageActivity.class);
        int fldPatientId = itemsBean.getFldPatientId();
        intent.putExtra(Code.SP.ID, fldPatientId);
        startActivity(intent);
    }

    @OnClick(R.id.iv_scan)
    public void scan() {
        startActivity(new Intent(context, QRCodeActivity.class));
    }
}
